import useFileManageStore from '@/store/modules/file-manage/index';
import { nextTick } from 'vue';
import { Modal, Message } from '@arco-design/web-vue';
import { HttpResponse } from '@/api/interceptor';
import { useThrottleFn } from '@vueuse/core';
import { download } from '@/utils/file';
import {
  FileAndFolderNodeMessage,
  FileMessage,
  FolderMessage,
} from '@/api/tree-folder';
import {
  FileVersion,
  addChildFolder,
  updateFolder,
  updateFile,
  fileRollback,
  fileDownload,
  FileAndFolderMessage,
  addFile,
  fileShare,
} from '../api';
import { getNodeById, isFolderRepeated } from './utils';

const store = useFileManageStore();

// 添加文件夹请求
async function addFolderRequest(
  currentFile: FileMessage,
  inputElement: HTMLInputElement,
  divElement: HTMLElement
) {
  const inputValue = inputElement.value;
  const param: FolderMessage = {
    name: inputValue,
    parentId: currentFile.id,
    projectId: currentFile.projectId,
    teamId: currentFile.teamId,
    type: currentFile.type,
  };

  // 名称为空校验
  if (inputValue === '') {
    divElement.remove();
    return;
  }

  // 名称重复校验
  const repeated = await isFolderRepeated(currentFile, inputValue);
  if (repeated) {
    inputElement.focus();
    Message.error('名称重复');
    return;
  }

  // 新增文件夹接口
  const res: any = await addChildFolder(param);
  const result = res as HttpResponse<any>;
  if (result.code === 8000000) {
    Message.success('新增成功');
    divElement.remove();
    store.getTreeChild(currentFile, false);
  }
}

// 添加文件夹按钮
export function addFolder(
  currentFile: FileMessage,
  currentElement: Element | null
) {
  if (!currentElement) return;
  // 在父元素下添加输入框
  const parentElem = currentElement.parentNode;
  const newDiv = document.createElement('div');
  newDiv.style.border = '1px solid rgb(var(--primary-6))';
  newDiv.style.padding = ' 4px 12px';
  const newElem = document.createElement('input');
  const textElement = currentElement.getElementsByClassName(
    'arco-tree-node-indent'
  );
  // 计算输入框位置和宽度
  const marginLeft = Math.min(textElement[0].clientWidth + 46, 100);
  newDiv.style.marginLeft = `${marginLeft}px`;
  newDiv.style.width = `calc(100% - ${marginLeft + 24}px)`;
  // 设置input样式
  newElem.style.width = '100%';
  newElem.style.border = '0';
  newElem.style.outline = '0';
  newDiv.appendChild(newElem);
  parentElem?.insertBefore(newDiv, currentElement.nextSibling);
  // input失焦触发事件
  newElem.addEventListener('blur', () => {
    addFolderRequest(currentFile, newElem, newDiv);
  });
  newElem.addEventListener(
    'keypress',
    useThrottleFn((event) => {
      if (event.key === 'Enter') {
        addFolderRequest(currentFile, newElem, newDiv);
      }
    }, 200)
  );
  // 输入框自动聚焦
  nextTick(() => {
    newElem.focus();
  });
}

// 文件夹重命名
export function renameFolder(currentFile: FileAndFolderNodeMessage) {
  store.setTreeRenameValue(currentFile.name || '');
  nextTick(() => {
    store.setRenameKey(currentFile.key || '');
  });
}

// 文件夹重命名请求
export async function renameFolderRequest(
  currentFile: FileAndFolderNodeMessage,
  renameInput: HTMLInputElement
) {
  // 名称没有变化或者名称为空表示退出编辑
  if (
    store.treeRenameValue === store.treeRenameBackup ||
    store.treeRenameValue === ''
  ) {
    store.setRenameKey(-1);
    store.setTreeRenameValue('');
    return;
  }
  // 名称重复校验
  const parentMessage: any = getNodeById(
    store.treeData,
    currentFile.parentId || ''
  );
  const repeated = await isFolderRepeated(parentMessage, store.treeRenameValue);
  if (repeated) {
    renameInput.focus();
    Message.error('名称重复');
    return;
  }

  const param: FolderMessage = {
    ...currentFile,
    name: store.treeRenameValue,
  };
  const res: any = await updateFolder(param);
  const result = res as HttpResponse<any>;
  if (result.code === 8000000) {
    Message.success('修改成功');
    store.setRenameKey(-1);
    store.setTreeRenameValue('');
    store.getTreeChild(parentMessage);
  }
}

/** 改变tree目录排序 */
export function order(currentFile: FileAndFolderNodeMessage, orderBy: string) {
  currentFile.children?.sort(
    (a: FileAndFolderNodeMessage, b: FileAndFolderNodeMessage) => {
      let result = 0;
      if (orderBy === 'date') {
        const valueA = new Date(a.createDate || '').getTime();
        const ValueB = new Date(b.createDate || '').getTime();
        result = valueA - ValueB;
      } else {
        result =
          (a.name?.localeCompare(b?.name || '') || 0) *
          (orderBy === 'asc' ? 1 : -1);
      }
      return result;
    }
  );
}

/** 显示版本列表抽屉 */
export function showVersions(currentFile: FileAndFolderNodeMessage) {
  store.setCurrentFIle(currentFile);
  store.getFileVersionData();
  store.setVersionDrawer(true);
}

/** 版本回退 */
export function rollback(version: string) {
  Modal.warning({
    title: '您确定要将该文件版本回退至当前选择版本V1吗？',
    content: '',
    width: 464,
    onOk: async () => {
      const res: any = await fileRollback(store.currentFile?.id, version);
      const result = res as HttpResponse<any>;
      if (result.code === 8000000) {
        store.getFileVersionData();
        store.getTableData(store.currentFolder || {}, false);
      }
    },
  });
}

/** 版本复制请求 */
async function versionCopyRequest(
  treeDataPromise: () => Promise<any>
): Promise<boolean> {
  const folderId: string = await treeDataPromise();
  const currentVersion = store.currentVersion || {};
  const fileMessage = {
    id: currentVersion?.fileId,
    name: currentVersion?.name,
    projectId: currentVersion?.projectId,
    teamId: currentVersion?.teamId,
    folderId,
    fileToken: currentVersion?.fileToken,
    description: currentVersion?.description,
    size: currentVersion?.size,
    type: currentVersion?.type,
    version: currentVersion?.version,
  };
  const res: any = await addFile(fileMessage);
  const result = res as HttpResponse<any>;
  if (result.code === 8000000) {
    Message.success('复制成功');
    return true;
  }
  return false;
}

/** 版本复制按钮 */
export function versionCopy(fileVersion: FileVersion) {
  store.setMoveModal(true);
  store.setCurrentVersion(fileVersion);
  store.setSendMove(versionCopyRequest);
}

/** 版本下载按钮 */
export async function versionDownload(fileVersion: FileVersion) {
  const res: any = await fileDownload(fileVersion.fileToken || '');
  download({ name: fileVersion.name || '' }, res.data);
}

/** 文件/文件夹移动请求 */
async function moveRequest(
  treeDataPromise: () => Promise<any>
): Promise<boolean> {
  const parentId: string = await treeDataPromise();
  if (!parentId) {
    Message.error('请选择目标文件夹');
    return false;
  }
  const currentFileOrFolder: FileAndFolderMessage = JSON.parse(
    JSON.stringify(store.currentFile)
  );
  let api;
  if (currentFileOrFolder.isFileOrFolder === 0) {
    api = updateFolder;
    currentFileOrFolder.parentId = parentId;
  } else {
    api = updateFile;
    currentFileOrFolder.folderId = parentId;
  }
  currentFileOrFolder.parentId = parentId;
  const res: any = await api(currentFileOrFolder);
  const result = res as HttpResponse<any>;
  if (result.code === 8000000) {
    Message.error('移动成功');
    return true;
  }
  return false;
}

/** 文件/文件夹移动按钮 */
export function move() {
  store.setMoveModal(true);
  store.setSendMove(moveRequest);
}

export function rename(index: number) {
  // TODO table 重命名按钮
  store.setRenameIndex(index);
}

export function renameRequest() {
  // TODO table 重命名接口调用
  store.setRenameIndex(-1);
}

export function batchDownload() {
  // TODO tableHead 批量下载按钮
}
export function batchSharing() {
  // TODO tableHead 批量分享按钮
  const res: any = {
    data: [
      {
        label: 'GIS',
        value: 'htt1ps://lanhuapp.com/',
      },
      {
        label: 'Shared',
        value: 'ht2tps://lanhuapp.com/',
      },
    ],
  };
  store.setShareModal(true, res.data);
}

export function upload(currentFolder: FolderMessage) {
  // TODO tree 上传按钮
  store.setUploadModal(true);
  store.setSelectedFolder(currentFolder);
  return currentFolder;
}

export async function downloadSource(currentFile: FileAndFolderNodeMessage) {
  // TODO table/tree 下载源文件按钮
  if (currentFile.isFileOrFolder) {
    // 文件
    const res: any = await fileDownload(currentFile.fileToken || '');
    download({ name: currentFile.name || '' }, res.data);
  } else {
    // 文件夹
  }
  return currentFile;
}

export function approve(currentFile: FileMessage) {
  // TODO table/tree 提交以供审阅按钮
  return currentFile;
}

export function createBypass(currentFile: FileMessage) {
  // TODO table/tree 创建附函按钮
  store.setEnclosureModal(true, currentFile);
  console.log(store.enclosureModal);
}

export async function share(id: any) {
  // TODO table分享按钮
  // const res: any = await fileShare(id);
  const res: any = {
    data: [
      {
        label: 'GIS',
        value: 'htt1ps://lanhuapp.com/',
      },
      {
        label: 'Shared',
        value: 'ht2tps://lanhuapp.com/',
      },
    ],
  };
  store.setShareModal(true, res.data);
}
